package com.lws.basic.view.text_watcher;

import android.text.Editable;
import android.text.TextWatcher;

/**
 * 将此监听器设置给textkView，可以保证用户只输入两位小数
 */

public class DecimalTextWatcher implements TextWatcher {

    private int maxDecimalDigit;

    public DecimalTextWatcher(int maxDecimalDigit) {
        this.maxDecimalDigit = maxDecimalDigit;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override
    public void afterTextChanged(Editable edt) {
        String temp = edt.toString();
        int posDot = temp.indexOf(".");//得到小数点起始位置
        if (posDot <= 0) return;//说明没有小数点
        //如果用户输入小数点后的第三位，直接删掉，不让用户输入小数点后第三位
        if (temp.length() - posDot - 1 > maxDecimalDigit) {
            edt.delete(posDot + maxDecimalDigit + 1, posDot + maxDecimalDigit + 2);
        }
    }
}
